<template>
    <van-nav-bar class="navbar">
        <template #left>
            <div class="left">
                <van-icon name="arrow-left" size="24" v-if="!props.isHome" @click="goBack" />
                <van-image :src="props.isHome ? Logo : Car" :class="props.isHome ? 'logo' : 'icon'"></van-image>
                <span v-if="!props.isHome">{{ props.categoryName }}</span>
            </div>
        </template>
        <template #right>
            <div class="right">
                <div class="address-menu" @click="showLocationSelector">
                    <span class="address">{{ currentCityName }}</span> <!-- 当前城市 -->
                    <van-icon name="arrow-down" class="address-icon" />
                </div>
                <van-icon :name="Bread_Menu" class="menu-icon" @click="showTypeSelector" />
            </div>
        </template>
    </van-nav-bar>

    <!-- 城市选择 -->
    <Location :current-city="store.currentCity" :active-city-id="activeCityId" :province-data="provinceData"
        :current-province="currentProvince" @update:currentProvince="updateCurrentProvince"
        @update:activeCityId="updateActiveCityId">
    </Location>
    <!-- 类型选择 -->
    <Type></Type>

</template>
<script setup>
import Logo from "/assets/logo.png" //首页左侧图
import Car from "/assets/car.png"  //其他页面左侧图
import Bread_Menu from "/assets/bread_menu.png" //菜单图标

import Location from "@/components/common/navbar/Location.vue";
import Type from "@/components/common/navbar/Type.vue";

import { ref, onMounted, computed } from "vue"
import { fetchCityPosition, fetchCityList } from "@/api/index.js"
import { handleCityData } from "@/tool/index.js";

// import { showToast } from "vant";

import { useStore } from '@/pinia/index.js'
const store = useStore()

import { useRouter } from "vue-router";
const router = useRouter()



const props = defineProps({
    categoryName: String,
    isHome: Boolean,
    leftArrow: Boolean,
});



const currentCityName = computed(() => store.currentCity.name)

const provinceData = ref([]);
const currentProvince = ref(null);
const activeCityId = ref(null);


onMounted(async () => {
    await getCityPosition() //定位当前城市
    await getCityList(); // 根据定位城市匹配完整信息

})

// 打开城市选择菜单
const showLocationSelector = () => {
    store.set_city_menu_show(true)
}


// 打开考试类型选择菜单
const showTypeSelector = () => {
    store.set_type_menu_show(true)
}

// 初始化城市定位
const getCityPosition = async () => {
    try {
        const { data: { currentWeatherInfo: { city } } } = await fetchCityPosition()
        console.log('定位城市:', city)
        // 只设置城市名称，code 等待 getCityList 中匹配
        store.set_current_city({ name: city, code: '' })
    }
    catch (e) {
        showToast(e);
    }
};


const getCityList = async () => {
    try {
        if (!store.provinceList || store.provinceList.length == 0) {
            const response = await fetchCityList()
            provinceData.value = handleCityData(response.initial)
            store.set_provinceList(provinceData.value)
        } else {
            provinceData.value = store.provinceList
        }

        //console.log("provinceData:", provinceData.value)
        // [ {firstLetter: 'A', code: '340000', name: '安徽省', cities: [{code: '340100', name: '合肥市'} ... ]} ...]



        // 确保在获取城市列表后再匹配定位城市
        if (provinceData.value.length > 0) {
            matchLocatedCity()
        }
    } catch (error) {
        console.error('获取城市列表失败:', error)
    }
}

// 匹配定位城市
const matchLocatedCity = () => {
    if (!currentCityName.value || !provinceData.value.length) return



    for (let province of provinceData.value) {
        const matchedCity = province.cities.find(city => {
            if (city.name === currentCityName.value) {
                return true
            }
            if (city.name === currentCityName.value + '市') {
                return true
            }
            if (city.name.endsWith('市') && city.name.slice(0, -1) === currentCityName.value) {
                return true
            }
            if (city.name.startsWith(currentCityName.value) &&
                (city.name.includes('自治州') ||
                    city.name.includes('地区') ||
                    city.name.includes('盟'))) {
                return true
            }
            return false
        })

        if (matchedCity) {

            console.log('匹配到城市:', matchedCity) //   {code: '460100', name: '海口市'}
            currentProvince.value = province

            activeCityId.value = matchedCity.code

            store.set_current_city({ name: currentCityName.value, code: matchedCity.code })


            break
        }
    }
}

// 更新当前省份
const updateCurrentProvince = (province) => {
    currentProvince.value = province
}

// 更新活动城市ID
const updateActiveCityId = (cityId) => {
    activeCityId.value = cityId
};


const goBack = () => {
    // window.history.back()
    router.go(-1)
}

</script>
<style lang="scss" scoped>
.navbar {
    position: sticky;
    width: 100%;
    height: 44px;

    .left {
        width: 180px;
        display: flex;
        flex-wrap: nowrap;
        align-items: center;
        justify-content: flex-start;
        gap: 0;

        .logo {}

        .icon {
            transform: scale(.6);
            margin: 0;
            padding: 0;
        }

        span {}



    }



    .right {
        display: flex;
        align-items: center;
        font-size: 16px;


        .address-menu {
            margin-right: 10px;


        }

        .menu-icon {
            font-size: 20px;

        }

    }
}
</style>